{% extends "base_lite.html" %}

{% block title %}图片库{% endblock %}

{% block additional_styles %}
<style>
/* 图片网格布局 */
.gallery-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
    gap: 1.5rem;
    margin-top: 2rem;
}

.gallery-item {
    background: var(--card-bg);
    border-radius: 12px;
    overflow: hidden;
    transition: all 0.3s ease;
    cursor: pointer;
    border: 1px solid var(--border);
    position: relative;
}

.gallery-item:hover {
    transform: translateY(-8px);
    box-shadow: 0 12px 30px rgba(0,0,0,0.15);
}

.gallery-image {
    width: 100%;
    height: 200px;
    object-fit: cover;
    background: #f8f9fa;
    transition: transform 0.3s ease;
}

.gallery-item:hover .gallery-image {
    transform: scale(1.05);
}

.gallery-info {
    padding: 1rem;
}

/* 图片查看器模态框 */
.image-viewer {
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(0,0,0,0.9);
    display: none;
    justify-content: center;
    align-items: center;
    z-index: 1000;
    padding: 2rem;
}

.viewer-content {
    position: relative;
    max-width: 90vw;
    max-height: 90vh;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.viewer-image {
    max-width: 100%;
    max-height: 80vh;
    object-fit: contain;
    border-radius: 8px;
    box-shadow: 0 8px 30px rgba(0,0,0,0.5);
}

.viewer-info {
    background: var(--card-bg);
    padding: 1rem 2rem;
    border-radius: 8px;
    margin-top: 1rem;
    min-width: 300px;
    text-align: center;
}

.viewer-close {
    position: absolute;
    top: -50px;
    right: 0;
    background: rgba(255,255,255,0.2);
    border: none;
    color: white;
    width: 40px;
    height: 40px;
    border-radius: 50%;
    font-size: 1.5rem;
    cursor: pointer;
    transition: background 0.3s ease;
}

.viewer-close:hover {
    background: rgba(255,255,255,0.3);
}

/* 导航按钮 */
.viewer-nav {
    position: absolute;
    top: 50%;
    transform: translateY(-50%);
    background: rgba(255,255,255,0.2);
    border: none;
    color: white;
    width: 50px;
    height: 50px;
    border-radius: 50%;
    font-size: 1.5rem;
    cursor: pointer;
    transition: all 0.3s ease;
}

.viewer-nav:hover {
    background: rgba(255,255,255,0.3);
    transform: translateY(-50%) scale(1.1);
}

.viewer-nav.prev {
    left: 2rem;
}

.viewer-nav.next {
    right: 2rem;
}

/* 搜索和筛选 */
.filter-section {
    display: flex;
    gap: 1rem;
    flex-wrap: wrap;
    align-items: center;
    margin-bottom: 2rem;
}

.view-toggle {
    display: flex;
    background: var(--card-bg);
    border-radius: 8px;
    padding: 0.25rem;
    border: 1px solid var(--border);
}

.view-toggle button {
    background: none;
    border: none;
    padding: 0.5rem 1rem;
    border-radius: 6px;
    cursor: pointer;
    transition: all 0.3s ease;
    color: var(--text);
}

.view-toggle button.active {
    background: var(--primary);
    color: white;
}

/* 列表视图 */
.gallery-list {
    display: none;
}

.gallery-list.active {
    display: block;
}

.list-item {
    background: var(--card-bg);
    border-radius: 8px;
    padding: 1rem;
    margin-bottom: 1rem;
    display: flex;
    align-items: center;
    gap: 1rem;
    border: 1px solid var(--border);
    transition: all 0.3s ease;
    cursor: pointer;
}

.list-item:hover {
    transform: translateY(-2px);
    box-shadow: 0 4px 15px rgba(0,0,0,0.1);
}

.list-thumbnail {
    width: 60px;
    height: 60px;
    object-fit: cover;
    border-radius: 6px;
    background: #f8f9fa;
}

.list-info {
    flex: 1;
}

/* 加载动画 */
.loading {
    text-align: center;
    padding: 3rem;
    color: var(--text-muted);
}

.loading-spinner {
    display: inline-block;
    width: 40px;
    height: 40px;
    border: 4px solid var(--border);
    border-top: 4px solid var(--primary);
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-bottom: 1rem;
}

@keyframes spin {
    0% { transform: rotate(0deg); }
    100% { transform: rotate(360deg); }
}

/* 响应式设计 */
@media (max-width: 768px) {
    .gallery-grid {
        grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
        gap: 1rem;
    }
    
    .filter-section {
        flex-direction: column;
        align-items: stretch;
    }
    
    .viewer-nav {
        width: 40px;
        height: 40px;
        font-size: 1.2rem;
    }
    
    .viewer-nav.prev {
        left: 1rem;
    }
    
    .viewer-nav.next {
        right: 1rem;
    }
}
</style>
{% endblock %}

{% block content %}
<div class="container">
    <div class="d-flex justify-content-between align-items-center mb-4">
        <h2 class="fw-bold">🖼️ 图片库</h2>
        <div class="d-flex gap-2">
            {% if session.role == 'admin' %}
                <a href="{{ url_for('admin_dashboard') }}" class="btn btn-primary btn-sm">
                    📊 管理面板
                </a>
            {% endif %}
            <a href="{{ url_for('logout') }}" class="btn btn-secondary btn-sm">
                🚪 退出
            </a>
        </div>
    </div>

    <!-- 搜索和筛选 -->
    <div class="filter-section">
        <div class="flex-1" style="min-width: 250px;">
            <input type="text" class="form-control" placeholder="🔍 搜索图片..." 
                   id="searchInput" onkeyup="filterImages()">
        </div>
        
        <select class="form-control" style="width: auto;" id="sortSelect" onchange="sortImages()">
            <option value="newest">📅 最新上传</option>
            <option value="oldest">📅 最早上传</option>
            <option value="largest">📏 文件最大</option>
            <option value="smallest">📏 文件最小</option>
            <option value="name">🔤 文件名称</option>
        </select>
        
        <div class="view-toggle">
            <button onclick="setViewMode('grid')" class="active" id="gridViewBtn">
                🏢 网格
            </button>
            <button onclick="setViewMode('list')" id="listViewBtn">
                📋 列表
            </button>
        </div>
        
        <button class="btn btn-outline btn-sm" onclick="refreshGallery()">
            🔄 刷新
        </button>
    </div>

    <!-- 统计信息 -->
    <div class="card mb-4" style="background: linear-gradient(135deg, rgba(var(--primary-rgb), 0.1), rgba(var(--secondary-rgb), 0.1));">
        <div class="text-center">
            <div style="display: flex; justify-content: center; gap: 2rem; flex-wrap: wrap;">
                <div>
                    <div style="font-size: 2rem; font-weight: bold; color: var(--primary);" id="totalCount">{{ images|length }}</div>
                    <div style="font-size: 0.875rem; color: var(--text-muted);">总图片数</div>
                </div>
                <div>
                    <div style="font-size: 2rem; font-weight: bold; color: var(--secondary);" id="filteredCount">{{ images|length }}</div>
                    <div style="font-size: 0.875rem; color: var(--text-muted);">显示数量</div>
                </div>
                <div>
                    <div style="font-size: 2rem; font-weight: bold; color: var(--success);">
                        {{ "%.1f"|format(images|map(attribute='size')|sum / 1024 / 1024) }}MB
                    </div>
                    <div style="font-size: 0.875rem; color: var(--text-muted);">总大小</div>
                </div>
            </div>
        </div>
    </div>

    <!-- 网格视图 -->
    <div class="gallery-grid" id="galleryGrid">
        {% for image in images %}
        <div class="gallery-item" data-filename="{{ image.filename }}" 
             data-upload-time="{{ image.upload_time.timestamp() }}"
             data-size="{{ image.size }}"
             onclick="openImageViewer({{ loop.index0 }})">
            <img src="{{ url_for('thumbnail_file', filename=image.thumbnail) }}" 
                 alt="{{ image.filename }}" class="gallery-image"
                 onerror="this.src=''">
            <div class="gallery-info">
                <div style="font-weight: 600; margin-bottom: 0.5rem; word-break: break-all; font-size: 0.9rem;">
                    {{ image.filename }}
                </div>
                <div style="font-size: 0.75rem; color: var(--text-muted); display: flex; justify-content: space-between; margin-bottom: 0.5rem;">
                    <span>📏 {{ image.width }}×{{ image.height }}</span>
                    <span>💾 {{ "%.1f"|format(image.size / 1024 / 1024) }}MB</span>
                </div>
                <div style="font-size: 0.75rem; color: var(--text-muted);">
                    📅 {{ image.upload_time.strftime('%Y-%m-%d %H:%M') }}
                </div>
            </div>
        </div>
        {% else %}
        <div style="grid-column: 1 / -1; text-align: center; padding: 4rem; color: var(--text-muted);">
            <div style="font-size: 5rem; margin-bottom: 2rem; opacity: 0.5;">📭</div>
            <h4 class="fw-bold mb-3">暂无图片</h4>
            <p>图片库中还没有任何图片</p>
            {% if session.role == 'admin' %}
                <a href="{{ url_for('admin_dashboard') }}" class="btn btn-primary mt-3">
                    📤 去上传图片
                </a>
            {% endif %}
        </div>
        {% endfor %}
    </div>

    <!-- 列表视图 -->
    <div class="gallery-list" id="galleryList">
        {% for image in images %}
        <div class="list-item" data-filename="{{ image.filename }}" 
             data-upload-time="{{ image.upload_time.timestamp() }}"
             data-size="{{ image.size }}"
             onclick="openImageViewer({{ loop.index0 }})">
            <img src="{{ url_for('thumbnail_file', filename=image.thumbnail) }}" 
                 alt="{{ image.filename }}" class="list-thumbnail"
                 onerror="this.src=''">
            <div class="list-info">
                <div style="font-weight: 600; margin-bottom: 0.25rem; word-break: break-all;">
                    {{ image.filename }}
                </div>
                <div style="font-size: 0.875rem; color: var(--text-muted); margin-bottom: 0.25rem;">
                    📏 {{ image.width }}×{{ image.height }} | 💾 {{ "%.1f"|format(image.size / 1024 / 1024) }}MB
                </div>
                <div style="font-size: 0.75rem; color: var(--text-muted);">
                    📅 {{ image.upload_time.strftime('%Y-%m-%d %H:%M:%S') }}
                </div>
            </div>
            <div style="font-size: 1.5rem; opacity: 0.6;">👁️</div>
        </div>
        {% endfor %}
    </div>
</div>

<!-- 图片查看器 -->
<div class="image-viewer" id="imageViewer">
    <div class="viewer-content">
        <button class="viewer-close" onclick="closeImageViewer()">✕</button>
        <button class="viewer-nav prev" onclick="previousImage()">‹</button>
        <button class="viewer-nav next" onclick="nextImage()">›</button>
        
        <img id="viewerImage" class="viewer-image" alt="">
        
        <div class="viewer-info">
            <div style="font-weight: 600; margin-bottom: 0.5rem; word-break: break-all;" id="viewerFilename"></div>
            <div style="font-size: 0.875rem; color: var(--text-muted); margin-bottom: 0.5rem;" id="viewerDimensions"></div>
            <div style="font-size: 0.875rem; color: var(--text-muted); margin-bottom: 1rem;" id="viewerTime"></div>
            <div class="d-flex gap-2 justify-content-center">
                <button class="btn btn-primary btn-sm" onclick="downloadImage()">
                    💾 下载
                </button>
                <button class="btn btn-outline btn-sm" onclick="copyImageUrl()">
                    🔗 复制链接
                </button>
            </div>
        </div>
    </div>
</div>

<script>
let currentImages = {{ images | tojson | safe }};
let filteredImages = [...currentImages];
let currentImageIndex = 0;
let currentViewMode = 'grid';

// 图片查看器
function openImageViewer(index) {
    currentImageIndex = index;
    updateViewer();
    document.getElementById('imageViewer').style.display = 'flex';
    document.body.style.overflow = 'hidden';
}

function closeImageViewer() {
    document.getElementById('imageViewer').style.display = 'none';
    document.body.style.overflow = '';
}

function updateViewer() {
    if (filteredImages.length === 0) return;
    
    const image = filteredImages[currentImageIndex];
    const viewerImage = document.getElementById('viewerImage');
    const viewerFilename = document.getElementById('viewerFilename');
    const viewerDimensions = document.getElementById('viewerDimensions');
    const viewerTime = document.getElementById('viewerTime');
    
    viewerImage.src = '{{ url_for("uploaded_file", filename="") }}' + image.filename;
    viewerFilename.textContent = image.filename;
    viewerDimensions.textContent = `📏 ${image.width}×${image.height} | 💾 ${(image.size / 1024 / 1024).toFixed(1)}MB`;
    
    const uploadTime = new Date(image.upload_time.$date);
    viewerTime.textContent = `📅 ${uploadTime.toLocaleString('zh-CN')}`;
}

function previousImage() {
    if (filteredImages.length === 0) return;
    currentImageIndex = (currentImageIndex - 1 + filteredImages.length) % filteredImages.length;
    updateViewer();
}

function nextImage() {
    if (filteredImages.length === 0) return;
    currentImageIndex = (currentImageIndex + 1) % filteredImages.length;
    updateViewer();
}

function downloadImage() {
    if (filteredImages.length === 0) return;
    const image = filteredImages[currentImageIndex];
    const link = document.createElement('a');
    link.href = '{{ url_for("uploaded_file", filename="") }}' + image.filename;
    link.download = image.filename;
    link.click();
}

function copyImageUrl() {
    if (filteredImages.length === 0) return;
    const image = filteredImages[currentImageIndex];
    const url = window.location.origin + '{{ url_for("uploaded_file", filename="") }}' + image.filename;
    navigator.clipboard.writeText(url).then(() => {
        showMessage('链接已复制到剪贴板！', 'success');
    });
}

// 搜索和筛选
function filterImages() {
    const searchTerm = document.getElementById('searchInput').value.toLowerCase();
    const galleryItems = document.querySelectorAll('.gallery-item, .list-item');
    let visibleCount = 0;
    
    filteredImages = currentImages.filter(image => {
        return image.filename.toLowerCase().includes(searchTerm);
    });
    
    galleryItems.forEach((item, index) => {
        const filename = item.dataset.filename.toLowerCase();
        if (filename.includes(searchTerm)) {
            item.style.display = '';
            visibleCount++;
        } else {
            item.style.display = 'none';
        }
    });
    
    document.getElementById('filteredCount').textContent = visibleCount;
}

// 排序
function sortImages() {
    const sortType = document.getElementById('sortSelect').value;
    const gridContainer = document.getElementById('galleryGrid');
    const listContainer = document.getElementById('galleryList');
    const items = [...document.querySelectorAll('.gallery-item, .list-item')];
    
    items.sort((a, b) => {
        switch (sortType) {
            case 'newest':
                return parseFloat(b.dataset.uploadTime) - parseFloat(a.dataset.uploadTime);
            case 'oldest':
                return parseFloat(a.dataset.uploadTime) - parseFloat(b.dataset.uploadTime);
            case 'largest':
                return parseInt(b.dataset.size) - parseInt(a.dataset.size);
            case 'smallest':
                return parseInt(a.dataset.size) - parseInt(b.dataset.size);
            case 'name':
                return a.dataset.filename.localeCompare(b.dataset.filename);
            default:
                return 0;
        }
    });
    
    // 重新排列DOM元素
    if (currentViewMode === 'grid') {
        items.forEach(item => {
            if (item.classList.contains('gallery-item')) {
                gridContainer.appendChild(item);
            }
        });
    } else {
        items.forEach(item => {
            if (item.classList.contains('list-item')) {
                listContainer.appendChild(item);
            }
        });
    }
    
    // 更新filteredImages数组的顺序
    filteredImages.sort((a, b) => {
        switch (sortType) {
            case 'newest':
                return new Date(b.upload_time.$date) - new Date(a.upload_time.$date);
            case 'oldest':
                return new Date(a.upload_time.$date) - new Date(b.upload_time.$date);
            case 'largest':
                return b.size - a.size;
            case 'smallest':
                return a.size - b.size;
            case 'name':
                return a.filename.localeCompare(b.filename);
            default:
                return 0;
        }
    });
}

// 视图切换
function setViewMode(mode) {
    currentViewMode = mode;
    const gridView = document.getElementById('galleryGrid');
    const listView = document.getElementById('galleryList');
    const gridBtn = document.getElementById('gridViewBtn');
    const listBtn = document.getElementById('listViewBtn');
    
    if (mode === 'grid') {
        gridView.style.display = 'grid';
        listView.classList.remove('active');
        gridBtn.classList.add('active');
        listBtn.classList.remove('active');
    } else {
        gridView.style.display = 'none';
        listView.classList.add('active');
        gridBtn.classList.remove('active');
        listBtn.classList.add('active');
    }
}

// 刷新画廊
function refreshGallery() {
    window.location.reload();
}

// 键盘快捷键
document.addEventListener('keydown', (e) => {
    const viewer = document.getElementById('imageViewer');
    if (viewer.style.display === 'flex') {
        switch (e.key) {
            case 'Escape':
                closeImageViewer();
                break;
            case 'ArrowLeft':
                previousImage();
                break;
            case 'ArrowRight':
                nextImage();
                break;
        }
    }
});

// 点击查看器外部关闭
document.getElementById('imageViewer').addEventListener('click', (e) => {
    if (e.target === e.currentTarget) {
        closeImageViewer();
    }
});

// 显示消息
function showMessage(message, type) {
    const alertDiv = document.createElement('div');
    alertDiv.className = `alert alert-${type}`;
    alertDiv.style.cssText = `
        position: fixed;
        top: 20px;
        right: 20px;
        z-index: 1001;
        max-width: 300px;
        animation: slideIn 0.3s ease;
    `;
    alertDiv.innerHTML = `
        <div style="display: flex; align-items: center; gap: 0.5rem;">
            ${type === 'success' ? '✅' : '❌'} ${message}
        </div>
    `;
    
    document.body.appendChild(alertDiv);
    
    setTimeout(() => {
        alertDiv.remove();
    }, 3000);
}
</script>
{% endblock %}
